<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog=true;isAdd=true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色" />
        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义列结构 -->
          <template v-slot="{row}">
            <!-- 开 1 关 0 -->
            <el-switch v-model="row.state" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述" />
        <el-table-column align="center" label="操作">
          <!-- 放置操作按钮 -->
          <template v-slot="{ row }">
            <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
            <el-button
              v-if="hasPerm('edit-role')"
              size="mini"
              type="text"
              @click="showEdit(row.id)"
            >编辑</el-button>
            <el-popconfirm
              v-if="hasPerm('del-role')"
              title="这是一段内容确定删除吗？"
              @onConfirm="confirmDel(row.id)"
            >
              <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height: 60px;" align="middle" justify="end">
        <el-pagination
          layout="prev, pager, next"
          :total="pageParams.total"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 放置弹出层 -->
    <el-dialog
      width="500px"
      :title="isAdd?'新增角色':'编辑角色'"
      :visible.sync="showDialog"
      @close="btnCancel"
    >
      <!-- 表单内容 -->
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px" @close="btnCancel">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <!-- 如果不需要校验 就不需要写 prop 属性 -->
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="end">
            <el-col :span="12">
              <el-button size="mini" type="primary" @click="addOrEdit">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 放置权限弹层 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <!-- 放置权限数据 -->
      <el-tree
        ref="permTree"
        node-key="id"
        :data="permissionData"
        :props="{label:'name'}"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
        check-strictly
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
        <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, addRole, updateRole, delRole, getRoleDetail, assignPerm } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      showDialog: false,
      isAdd: true, // 区分编和新的，true 代表是添加，false 代表是编辑
      list: [],
      // 分页信息
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      // 声明数据和规则
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null,
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows // 赋值数据
      this.pageParams.total = total
    },
    // 切换分页时 请求新的数据
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值当前页码
      this.getRoleList()
    },
    // 新增Or编辑角色
    async addOrEdit() {
      this.$refs.roleForm.validate(async(isOK) => {
        if (isOK) {
          // 校验通过之后，判断是否新增
          if (this.isAdd) {
            await addRole(this.roleForm)
          } else {
            await updateRole(this.roleForm)
          }
          this.$message.success(`${this.isAdd ? '新增' : '更新'}角色成功`)
          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    // 点击取消
    btnCancel() {
      this.roleForm = this.$options.data().roleForm
      this.$refs.roleForm.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    // 点击编辑
    async showEdit(id) {
      // 利用id调接口拿到当前角色的详情
      const data = await getRoleDetail(id)
      // 利用角色详情填充表单
      this.roleForm = data
      // 把区分是否新增的变量设置为false，并把弹层展示出来
      this.isAdd = false
      this.showDialog = true
    },
    // 删除角色
    async confirmDel(id) {
      await delRole(id) // 后端删除
      // 删除的如果是最后一个
      if (this.list.length === 1) this.pageParams.page--
      this.getRoleList()
    },
    // 分配权限
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
      this.showPermissionDialog = true
    },
    // 点击确定时触发
    async btnPermissionOK() {
      await assignPerm({ id: this.currentRoleId, permIds: this.$refs.permTree.getCheckedKeys() })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>

<style scoped>
.role-operate{
  padding: 10px;
}
</style>
